/**
 * Project Name:YCApiServer-Api
 * File Name:WorkZanService.java
 * Package Name:com.yc.music.service.service103
 * Date:2016年5月19日上午10:44:23
 * Copyright (c) 2016 
 *
 */
package com.yc.music.service.service103;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import com.alibaba.fastjson.JSONObject;
import com.yc.music.common.context.YcContext;
import com.yc.music.common.push.YcPush;
import com.yc.music.common.util.BindingResultUtil;
import com.yc.music.context.YtConstant;
import com.yc.music.mapper.cache.UserCacheMapper;
import com.yc.music.mapper.cache.WorkCacheMapper;
import com.yc.music.mapper.dao.LyricsMapper;
import com.yc.music.mapper.dao.PushMessageFlowMapper;
import com.yc.music.mapper.dao.WorkMapper;
import com.yc.music.mapper.dao.WorkZanMapper;
import com.yc.music.model.OptWork;
import com.yc.music.model.YcPushMassageFlow;
import com.yc.music.model.musicLyrics.MusicLyrics;
import com.yc.music.model.musicWork.WorkOpenDetail;
import com.yc.music.model.musicuser.MusicUserVo;

import cn.jpush.api.push.PushResult;

/**
 * ClassName: WorkZanService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2016年5月19日 上午10:44:23 <br/>
 *
 * @author panguixiang
 * @version 
 */
@Service
public class WorkZanService {
	private static Logger logger = Logger.getLogger(WorkZanService.class);

	@Autowired
	private WorkZanMapper workZanMapper;
	
	@Autowired
	private WorkMapper workMapper;
	
	@Autowired
	private LyricsMapper lyricsMapper;
	
	@Autowired
	private UserCacheMapper userCacheMapper;
	
	@Autowired
	private WorkCacheMapper workCacheMapper;
	
	
	@Autowired
	private PushMessageFlowMapper pushMessageFlowMapper;
	
	
	/**
	 * 
	 * optWorkZan:(歌词，歌曲， 点赞). <br/> 
	 *
	 * @author panguixiang
	 * @param opt
	 * @param binding
	 * @param result
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Map<String,Object> optWorkZan(OptWork opt, BindingResult binding, Map<String,Object> result) throws Exception {
		String valiterMsg = BindingResultUtil.getBindErrorMsg(binding);
		if(StringUtils.isNotBlank(valiterMsg)) {
			result.put(YcContext.CODE, 400);
			result.put(YcContext.MESSAGE, valiterMsg);
			result.put(YcContext.DATA,YcContext.EMPTY_STRING);
			return result;
		}
		//修复由于存储过程delete操作不成功导致出现点赞数量出错的问题
		//先查询是否点过赞
		int count=workZanMapper.getMusicZanCountByUidAndWId(opt.getWork_id(), opt.getUser_id(), opt.getWtype());
		logger.info("获取信息count"+count);
		if (count>0) {
//			workZanMapper.proWorkZan(opt);
			//iszan 1表示点赞，0表示取消点赞
			if (1==opt.getWtype()) {
				workMapper.updateMusicZan(opt.getWork_id(), 0);
				logger.info("执行取消歌曲点赞");
			}else{
				lyricsMapper.updateMusicZan(opt.getWork_id(), 0);
				logger.info("执行取消歌词点赞");
			}
		    //如果赞过则直接删除关联记录
			workZanMapper.deleteWorkZan(opt);
			logger.info("已经点赞记录则删除");
		}else{
//			workZanMapper.proWorkZan(opt);
			if (1==opt.getWtype()) {
				workMapper.updateMusicZan(opt.getWork_id(), 1);
				logger.info("执行歌曲点赞");
			}else{
				lyricsMapper.updateMusicZan(opt.getWork_id(), 1);
				logger.info("执行歌词点赞");
			}
			workZanMapper.insertWorkZan(opt);
			logger.info("未点赞插入点赞");
		}
		result.put(YcContext.CODE, 200);
		result.put(YcContext.MESSAGE, YcContext.EMPTY_STRING);
		result.put(YcContext.DATA,opt.getResult());
		return result;
	}
	
	
	/**
	 * 
	 * optWorkZan:(歌词，歌曲， 点赞,增加推送). <br/> 
	 *
	 * @author qinhaiguan
	 * @param opt
	 * @param binding
	 * @param result
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Map<String,Object> optWorkZan22(OptWork opt, BindingResult binding, Map<String,Object> result) throws Exception {
		String valiterMsg = BindingResultUtil.getBindErrorMsg(binding);
		if(StringUtils.isNotBlank(valiterMsg)) {
			result.put(YcContext.CODE, 400);
			result.put(YcContext.MESSAGE, valiterMsg);
			result.put(YcContext.DATA,YcContext.EMPTY_STRING);
			return result;
		}
		
		String message=null;
		//修复由于存储过程delete操作不成功导致出现点赞数量出错的问题
		//先查询是否点过赞
		int count=workZanMapper.getMusicZanCountByUidAndWId(opt.getWork_id(), opt.getUser_id(), opt.getWtype());
		logger.info("获取信息count"+count);
		if (count>0) {
//			workZanMapper.proWorkZan(opt);
			//iszan 1表示点赞，0表示取消点赞
			if (1==opt.getWtype()) {
				workMapper.updateMusicZan(opt.getWork_id(), 0);
				logger.info("执行取消歌曲点赞");
				
			}else{
				lyricsMapper.updateMusicZan(opt.getWork_id(), 0);
				logger.info("执行取消歌词点赞");
			}
		    //如果赞过则直接删除关联记录
			workZanMapper.deleteWorkZan(opt);
			logger.info("已经点赞记录则删除");
			message=YtConstant.YUESHUPO_ZAN_CANCLE;
		}else{
//			workZanMapper.proWorkZan(opt);
			if (1==opt.getWtype()) {
				workMapper.updateMusicZan(opt.getWork_id(), 1);
				logger.info("执行歌曲点赞");
			}else{
				lyricsMapper.updateMusicZan(opt.getWork_id(), 1);
				logger.info("执行歌词点赞");
			}
			workZanMapper.insertWorkZan(opt);
			logger.info("未点赞插入点赞");
			message=YtConstant.YUESHUPO_ZAN_SAVE;
			
			//***********增加推送部分****************
			
			MusicUserVo  userVo=userCacheMapper.getCacheUservo(opt.getUser_id());
			
			//类型 1=歌曲，2=歌词
			if (1==opt.getWtype()) {
				WorkOpenDetail work=workCacheMapper.getWorOpenDetailById(opt.getWork_id());
				//针对一个人一个作品只第一次的时候推送
				int pushCount=pushMessageFlowMapper.getCountPushMessage(opt.getUser_id(),opt.getTarget_uid(), opt.getWork_id(), 1, YtConstant.PUSH_TYPE_ZAN);
				String msgIdAnd=null;
				String msgIdIOS=null;
				YcPushMassageFlow flow =new YcPushMassageFlow();
				if (0==pushCount) {
					//推送给android平台
					msgIdAnd=this.pushZanAndroid(String.valueOf(opt.getTarget_uid()), userVo.getNickname(), work.getTitle());
					if (null!=msgIdAnd) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_ANDROID);
						flow.setMsgid(msgIdAnd);
					}
					//推送给IOS平台
					msgIdIOS=this.pushZanIOS(String.valueOf(opt.getTarget_uid()), userVo.getNickname(), work.getTitle());
					if (null!=msgIdIOS) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_IOS);
						flow.setMsgid(msgIdIOS);
					}
					
					if (null==msgIdAnd&&null==msgIdIOS) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_NULL);
						flow.setMsgid(YtConstant.JPUSH_KEY_MSGID_NULL);
						
					}
				}
				//记录推送流水
				flow.setUid(opt.getUser_id());
				flow.setOtheruid(opt.getTarget_uid());
				flow.setWorkid(opt.getWork_id());
				flow.setWorktype(1);
				flow.setPushtype(YtConstant.PUSH_TYPE_ZAN);
				pushMessageFlowMapper.savePushMessageFlow(flow);
			}else{
				MusicLyrics lyrics =lyricsMapper.getMusicLyricsById(opt.getWork_id());
				//针对一个人一个作品只第一次的时候推送
				int pushCount=pushMessageFlowMapper.getCountPushMessage(opt.getUser_id(),opt.getTarget_uid(), opt.getWork_id(), 2, YtConstant.PUSH_TYPE_ZAN);
				String msgIdAnd=null;
				String msgIdIOS=null;
				YcPushMassageFlow flow =new YcPushMassageFlow();
				if (0==pushCount) {
					//推送给android平台
					msgIdAnd=this.pushZanAndroid(String.valueOf(opt.getTarget_uid()), userVo.getNickname(), lyrics.getTitle());
					if (null!=msgIdAnd) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_ANDROID);
						flow.setMsgid(msgIdAnd);
					}
					//推送给IOS平台
					msgIdIOS=this.pushZanIOS(String.valueOf(opt.getTarget_uid()), userVo.getNickname(), lyrics.getTitle());
					if (null!=msgIdIOS) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_IOS);
						flow.setMsgid(msgIdIOS);
					}
					
					if (null==msgIdAnd&&null==msgIdIOS) {
						flow.setPlatform(YtConstant.JPUSH_PLATFORM_NULL);
						flow.setMsgid(YtConstant.JPUSH_KEY_MSGID_NULL);
						
					}
				}
				//记录推送流水
				flow.setUid(opt.getUser_id());
				flow.setOtheruid(opt.getTarget_uid());
				flow.setWorkid(opt.getWork_id());
				flow.setWorktype(2);
				flow.setPushtype(YtConstant.PUSH_TYPE_ZAN);
				pushMessageFlowMapper.savePushMessageFlow(flow);
					
			}
			
		}
		result.put(YcContext.CODE, 200);
		result.put(YcContext.MESSAGE, YcContext.EMPTY_STRING);
		result.put(YcContext.DATA,message);
		return result;
	}
	
	
	private String pushZanAndroid(String uid,String userName,String title){
		logger.info("开始推送点赞消息Android>>>>>>推送给用户id:"+uid+",用户名:"+userName+",作品名:"+title);
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type", YtConstant.PUSH_TYPE_ZAN);
		param.put("title",YtConstant.YINCHAO);
		param.put("content",YtConstant.PUSH_TITLE_ZAN.replaceAll("U", userName).replaceAll("W", title));
		String pushMessage=JSONObject.toJSONString(param);
		PushResult re=YcPush.ycSendPushAndroid(String.valueOf(uid), pushMessage);
		logger.info("推送点赞消息返回结果Android:"+re);
		String msgId=null;
		if (null!=re) {
			msgId=JSONObject.parseObject(JSONObject.toJSONString(re)).getString(YtConstant.JPUSH_KEY_MSGID);
		}
		return msgId;
	}
	
	private String pushZanIOS(String uid,String userName,String title){
		logger.info("开始推送点赞消息IOS>>>>>>推送给用户id:"+uid+",用户名:"+userName+",作品名:"+title);
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type", YtConstant.PUSH_TYPE_ZAN);
		param.put("title",YtConstant.YINCHAO);
		param.put("content",YtConstant.PUSH_TITLE_ZAN.replaceAll("U", userName).replaceAll("W", title));
		String pushMessage=JSONObject.toJSONString(param);
		PushResult re=YcPush.ycSendPushIOS(String.valueOf(uid), pushMessage);
		logger.info("推送点赞消息返回结果IOS:"+re);
		String msgId=null;
		if (null!=re) {
			msgId=JSONObject.parseObject(JSONObject.toJSONString(re)).getString(YtConstant.JPUSH_KEY_MSGID);
		}
		return msgId;
	}
	
}
